<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="queryParams.menuName" placeholder="请输入菜单名称" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="菜单状态" clearable style="width: 240px">
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"><el-icon><Search /></el-icon>搜索</el-button>
          <el-button @click="resetQuery"><el-icon><Refresh /></el-icon>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="table-container">
      <template #header>
        <div class="card-header">
          <span>菜单列表</span>
          <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>新增</el-button>
        </div>
      </template>

      <!-- 菜单表格树 -->
      <el-table
        v-loading="loading"
        :data="menuList"
        row-key="menuId"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="menuName" label="菜单名称" :show-overflow-tooltip="true" />
        <el-table-column prop="icon" label="图标" align="center" width="100">
          <template #default="scope">
            <el-icon v-if="scope.row.icon">
              <component :is="scope.row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" width="60" align="center" />
        <el-table-column prop="perms" label="权限标识" :show-overflow-tooltip="true" />
        <el-table-column prop="path" label="路由地址" :show-overflow-tooltip="true" />
        <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
              {{ scope.row.status === 0 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleAdd(scope.row)" v-if="scope.row.menuType !== 'F'">
              新增
            </el-button>
            <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="680px" append-to-body>
      <el-form ref="menuForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级菜单">
          <tree-select
            v-model="form.parentId"
            :options="menuOptions"
            :normalizer="normalizer"
            placeholder="选择上级菜单"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="form.menuType">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item v-if="form.menuType !== 'F'" label="路由地址" prop="path">
          <el-input v-model="form.path" placeholder="请输入路由地址" />
        </el-form-item>
        <el-form-item v-if="form.menuType === 'C'" label="组件路径" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item v-if="form.menuType !== 'M'" label="权限标识" prop="perms">
          <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="50" />
        </el-form-item>
        <el-form-item v-if="form.menuType !== 'F'" label="菜单图标">
          <el-popover
            placement="bottom-start"
            trigger="click"
            width="460"
            popper-class="icons-container"
          >
            <template #reference>
              <el-input v-model="form.icon" placeholder="点击选择图标" readonly>
                <template #prefix>
                  <el-icon v-if="form.icon">
                    <component :is="form.icon" />
                  </el-icon>
                  <el-icon v-else><Picture /></el-icon>
                </template>
              </el-input>
            </template>
            <div class="icon-body">
              <div class="icon-list">
                <div
                  v-for="(item, index) in iconList"
                  :key="index"
                  @click="selectedIcon(item)"
                  class="icon-item"
                >
                  <el-icon>
                    <component :is="item" />
                  </el-icon>
                  <span>{{ item }}</span>
                </div>
              </div>
            </div>
          </el-popover>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { Search, Plus, Refresh, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TreeSelect from '@/components/TreeSelect/index.vue'

// 这里需要导入所有图标，实际项目中可以整理一份图标列表
import * as Icons from '@element-plus/icons-vue'

// 加载状态
const loading = ref(false)

// 查询参数
const queryParams = ref({
  menuName: undefined,
  status: undefined
})

// 表单参数
const form = ref({
  menuId: undefined,
  parentId: 0,
  menuName: undefined,
  icon: undefined,
  menuType: 'M',
  orderNum: 0,
  perms: undefined,
  path: undefined,
  component: undefined,
  status: 0
})

// 表单校验规则
const rules = {
  menuName: [
    { required: true, message: '菜单名称不能为空', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '菜单顺序不能为空', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '路由地址不能为空', trigger: 'blur' }
  ]
}

// 对话框状态
const dialog = reactive({
  visible: false,
  title: ''
})

// 菜单表格数据
const menuList = ref([
  {
    menuId: 1,
    menuName: '系统管理',
    icon: 'Setting',
    orderNum: 1,
    perms: '',
    path: '/system',
    component: '',
    status: 0,
    createTime: '2023-01-01 00:00:00',
    children: [
      {
        menuId: 2,
        menuName: '用户管理',
        icon: 'User',
        orderNum: 1,
        perms: 'system:user:list',
        path: 'user',
        component: 'system/user/index',
        status: 0,
        createTime: '2023-01-01 00:00:00',
        children: [
          {
            menuId: 8,
            menuName: '用户查询',
            icon: '',
            orderNum: 1,
            perms: 'system:user:query',
            path: '',
            component: '',
            status: 0,
            createTime: '2023-01-01 00:00:00',
            menuType: 'F'
          },
          {
            menuId: 9,
            menuName: '用户新增',
            icon: '',
            orderNum: 2,
            perms: 'system:user:add',
            path: '',
            component: '',
            status: 0,
            createTime: '2023-01-01 00:00:00',
            menuType: 'F'
          }
        ]
      },
      {
        menuId: 3,
        menuName: '角色管理',
        icon: 'UserFilled',
        orderNum: 2,
        perms: 'system:role:list',
        path: 'role',
        component: 'system/role/index',
        status: 0,
        createTime: '2023-01-01 00:00:00'
      },
      {
        menuId: 4,
        menuName: '菜单管理',
        icon: 'Menu',
        orderNum: 3,
        perms: 'system:menu:list',
        path: 'menu',
        component: 'system/menu/index',
        status: 0,
        createTime: '2023-01-01 00:00:00'
      }
    ]
  },
  {
    menuId: 5,
    menuName: '车辆管理',
    icon: 'Van',
    orderNum: 2,
    perms: '',
    path: '/car',
    component: '',
    status: 0,
    createTime: '2023-01-01 00:00:00',
    children: [
      {
        menuId: 6,
        menuName: '车辆列表',
        icon: 'List',
        orderNum: 1,
        perms: 'car:list:list',
        path: 'list',
        component: 'car/list/index',
        status: 0,
        createTime: '2023-01-01 00:00:00'
      },
      {
        menuId: 7,
        menuName: '车辆检查',
        icon: 'View',
        orderNum: 2,
        perms: 'car:inspection:list',
        path: 'inspection',
        component: 'car/inspection/index',
        status: 0,
        createTime: '2023-01-01 00:00:00'
      }
    ]
  }
])

// 菜单下拉选项
const menuOptions = ref([])

// 图标列表
const iconList = ref([])

// TreeSelect normalizer
const normalizer = (node) => {
  return {
    id: node.menuId,
    label: node.menuName,
    children: node.children
  }
}

// 在组件挂载时获取数据
onMounted(() => {
  getList()
  getMenuOptions()
  getIconList()
})

// 获取所有图标
function getIconList() {
  iconList.value = Object.keys(Icons)
}

// 获取菜单列表
function getList() {
  loading.value = true
  // 这里应该调用后端接口获取数据
  // 模拟API调用
  setTimeout(() => {
    // 使用模拟数据
    loading.value = false
  }, 500)
}

// 获取下拉菜单树选项
function getMenuOptions() {
  // 这里应该调用API获取菜单选项
  // 现在使用前端模拟数据
  menuOptions.value = [
    {
      menuId: 0,
      menuName: '主目录',
      children: []
    }
  ]
  // 将menuList添加到选项中
  menuOptions.value[0].children = menuList.value
}

// 选择图标
function selectedIcon(name) {
  form.value.icon = name
}

// 搜索按钮操作
function handleQuery() {
  getList()
}

// 重置按钮操作
function resetQuery() {
  queryParams.value = {
    menuName: undefined,
    status: undefined
  }
  handleQuery()
}

// 新增按钮操作
function handleAdd(row) {
  resetForm()
  if (row != null && row.menuId) {
    form.value.parentId = row.menuId
  } else {
    form.value.parentId = 0
  }
  dialog.visible = true
  dialog.title = '添加菜单'
}

// 修改按钮操作
function handleUpdate(row) {
  resetForm()
  getMenu(row.menuId)
  dialog.visible = true
  dialog.title = '修改菜单'
}

// 表单重置
function resetForm() {
  form.value = {
    menuId: undefined,
    parentId: 0,
    menuName: undefined,
    icon: undefined,
    menuType: 'M',
    orderNum: 0,
    perms: undefined,
    path: undefined,
    component: undefined,
    status: 0
  }
}

// 获取菜单详情
function getMenu(menuId) {
  // 这里应该调用API获取菜单详情
  // 现在使用前端模拟数据
  const findMenu = (list, id) => {
    for (let i = 0; i < list.length; i++) {
      if (list[i].menuId === id) {
        return list[i]
      }
      if (list[i].children && list[i].children.length > 0) {
        const res = findMenu(list[i].children, id)
        if (res) return res
      }
    }
    return null
  }
  
  const menu = findMenu(menuList.value, menuId)
  if (menu) {
    form.value = { ...menu }
  }
}

// 提交按钮
function submitForm() {
  // 这里应该调用创建或更新的API
  ElMessage.success(form.value.menuId ? '修改成功' : '新增成功')
  dialog.visible = false
  getList()
}

// 删除按钮操作
function handleDelete(row) {
  ElMessageBox.confirm('是否确认删除名称为"' + row.menuName + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用删除的API
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 监听表单菜单类型变化
watch(() => form.value.menuType, (val) => {
  if (val === 'F') {
    form.value.path = ''
    form.value.component = ''
    form.value.icon = ''
  }
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 15px;
}

.table-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.icon-body {
  width: 100%;
  padding: 10px;
}

.icon-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 5px;
  width: 80px;
  height: 70px;
  cursor: pointer;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  .el-icon {
    font-size: 24px;
    margin-bottom: 5px;
  }
  
  span {
    font-size: 12px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
}
</style> 